w<template>
  <div class="content">

    <div ref="searchRef">
      <el-form :inline="true" :model="formInline" class="grids gridColumns5">
        <el-form-item label="年份">
          <DatePicker v-model="formInline.year" type="year"></DatePicker>
        </el-form-item>
        <el-form-item label="订单流水号">
          <el-input v-model="formInline.ddlsh" placeholder="请输入订单流水号" clearable @change="search" />
        </el-form-item>
        <el-form-item label="发票号码">
          <el-input v-model="formInline.qdfphm" placeholder="请输入发票号码" clearable @change="search" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formInline.gmfMobile" placeholder="请输入手机号" clearable @change="search" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formInline.gmfEmail" placeholder="请输入邮箱" clearable @change="search" />
        </el-form-item>
        <el-form-item label="开票状态">
          <el-select v-model="formInline.status" placeholder="请选择开票状态" @change="search" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="init">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="actionBtn">
        <el-button type="primary" @click="proxy.$refs.inputFile.click()" plain>更新模板</el-button>
        <el-button type="primary" @click="downLoadTemplate" plain>下载模板</el-button>
        <el-button type="primary" @click="proxy.$refs.fileClick.click()" plain :loading="fileLoading">导入模板</el-button>
        <el-button type="primary" :disabled="!selectedArr.length" @click="exportExcel" plain :loading="fileLoading">导出</el-button>
        <el-button type="danger" plain :disabled="!selectedArr.length" @click="batchDelete">批量删除</el-button>
        <!-- <el-button type="danger" @click="clearAll">清空全部数据</el-button> -->
      </div>
    </div>

    <el-table :max-height="tableHeight" :data="tableParams.rows" v-loading="loading" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" />
      <el-table-column prop="ddlsh" label="订单流水号" width="150" />
      <el-table-column prop="gmfMobile" label="课程名称" width="350" show-overflow-tooltip>
        <template #default="scope">{{ curriculumFormat(scope.row.curriculum_info.curriculum_id) }}</template>
      </el-table-column>
      <el-table-column prop="gmfMc" label="购买方名称" width="300" />
      <el-table-column prop="gmfNsrsbh" label="购买方纳税人识别号" width="200" />
      <el-table-column prop="gmfMobile" label="购买方手机号" min-width="150">
        <template #default="scope">{{ scope.row.gmfMobile||scope.row.invoiceUser_info.mobile }}</template>
      </el-table-column>
      <el-table-column prop="gmfEmail" label="购买方邮箱" width="220" show-overflow-tooltip />
      <el-table-column label="商品金额">
        <template #default="scope">{{ proxy.$utils.formatNumber(scope.row.detailParam[0].je) }}</template>
      </el-table-column>
      <el-table-column label="税率">
        <template #default="scope">{{ scope.row.detailParam[0].slv * 100||1 }}%</template>
      </el-table-column>
      <el-table-column label="开票申请时间" width="200">
        <template #default="scope">{{ proxy.$utils.dateTimeFormateFn(scope.row.add_time||scope.row._add_time, "all") }}</template>
      </el-table-column>
      <el-table-column label="开票状态" prop="_status" width="150" />
      <el-table-column label="发票号码" prop="qdfphm" width="180" />
      <el-table-column label="开票异常原因" prop="ycyy" min-width="250" align="center" />
      <el-table-column label="操作" fixed="right" width="150" align="center">
        <template #default="scope">
          <div class="button" v-if="scope.row.status != 2" @click="handleClick(scope.row, 1)">重新开票</div>
          <div class="button" v-if="scope.row.pdf" @click="handleClick(scope.row,2)">下载</div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="tableParams['total']" :total="tableParams['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <input type="file" @change="handleFileUpload" v-show="false" ref="inputFile" />
    <input type="file" @change="handleFileImport" v-show="false" ref="fileClick" />

    <el-dialog v-model="dialogVisible" title="导入失败列表" width="500" :before-close="handleClose">
      <el-table :data="errList">
        <el-table-column property="ddlsh" label="订单流水号" />
        <el-table-column prop="errText" label=" 失败原因" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
import { ref } from "vue";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
let formInline = ref({
  year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
  pageIndex: 1,
  pageSize: 50,
  ddlsh: "",
  status: "",
  qdfphm: "",
  gmfMobile: "",
  gmfEmail: "",
  type: "admin",
});
let loading = ref(false);
let fileLoading = ref(false); //文件上传loading
let tableParams = ref({});
let options = ref([
  { label: "待审核", value: 0 },
  { label: "开票中", value: 1 },
  { label: "开具成功", value: 2 },
  { label: "开具失败", value: 3 },
  { label: "作废已申请", value: 4 },
  { label: "作废中", value: 5 },
  { label: "已作废", value: 6 },
  { label: "作废失败", value: 7 },
  { label: "已开未生成PDF（税控电票）", value: 8 },
  { label: "已审核", value: 9 },
  { label: "待扫码", value: 10 },
  { label: "已追回", value: 11 },
  { label: "需要登录", value: 1004 },
  { label: "需要认证", value: 1003 },
]);
let selectedArr = ref([]); //选中的数据
let dialogVisible = ref(false); //弹窗
let errList = ref([]); //导入错误列表
let searchHeight = ref(0);
let courses = ref([]); //所有课程

let tableHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 55 - searchHeight.value;
  return `${hei}px`;
});

onMounted(() => {
  search();
  geCourse();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
});

function curriculumFormat(id) {
  let index = proxy.$utils.findIndexByField(courses.value, "_id", id);
  return index > -1 ? courses.value[index].name : "";
}

async function geCourse() {
  courses.value = await proxy.$apis.course({
    type: "query",
    data: { allData: true },
  });
  console.log("所有课程", courses.value);
}

async function clearAll() {
  let resp = await proxy.$utils.confirmTips("是否确定清空全部数据?");
  if (!resp) return;
  await proxy.$apis.invoicingRecord({
    type: "clearAll",
  });
  proxy.$utils.showToast("清空成功");
  init();
}

async function handleFileUpload(event) {
  let file = {
    name: "",
    path: "",
    type: "invoice",
  };
  const files = event.target.files;
  file.name = files[0].name;
  file.path = await counter.uploadFile(files[0]);
  await proxy.$apis.fileTemplate({
    data: file,
    type: "update",
  });
  proxy.$utils.showToast("上传成功");
}

async function downLoadTemplate() {
  let resp = await proxy.$apis.fileTemplate({
    data: { type: "invoice" },
    type: "downLoad",
  });
  window.location.href = resp;
}

async function handleFileImport(event) {
  try {
    fileLoading.value = true;
    const files = event.target.files;
    let file = files[0];
    let list = [];
    let resp = await proxy.$utils.fileToJson(file);
    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      if (index) {
        list.push({
          ddlsh: element[0],
          gmfMc: element[1],
          gmfNsrsbh: element[2],
          gmfMobile: element[3],
          gmfEmail: element[4],
          detailParam: [
            {
              spmc: "培训费",
              je: element[5],
            },
          ],
          _add_time: proxy.$utils.getTimeFn(element[6]),
          status: 2,
          _status: "开具成功",
          qdfphm: element[7],
          pdf: element[8],
        });
      }
    }
    let errorList = await proxy.$apis.fileTemplate({
      data: { type: "invoice", list },
      type: "import",
    });
    if (errorList && errorList.length) {
      errList.value = errorList;
      dialogVisible.value = true;
    } else {
      proxy.$utils.showToast("导入成功");
    }
    init();
  } catch (error) {
    console.log("啥毛病", error);
  } finally {
    fileLoading.value = false;
  }
}

function handleClose() {
  errList.value = [];
  dialogVisible.value = false;
}

function handleSelectionChange(val) {
  selectedArr.value = proxy.$utils.deepcopy(val);
}

async function batchDelete() {
  let resp = await proxy.$utils.confirmTips("是否确定批量删除?");
  if (!resp) return;
  for (let index = 0; index < selectedArr.value.length; index++) {
    const element = selectedArr.value[index];
    await proxy.$apis.invoicingRecord({
      type: "del",
      data: element._id,
    });
  }
  proxy.$utils.showToast("删除成功");
  getInfo();
}

let search = () => {
  formInline.value.pageIndex = 1;
  getInfo();
};

let init = () => {
  formInline.value = {
    year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
    pageIndex: 1,
    pageSize: 10,
    ddlsh: "",
    status: "",
    qdfphm: "",
    gmfMobile: "",
    gmfEmail: "",
    type: "admin",
  };
  getInfo();
};
let getInfo = async () => {
  try {
    loading.value = true;
    tableParams.value = await proxy.$apis.invoicingRecord({
      type: "list",
      data: formInline.value,
    });
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

let handleClick = async (row, num) => {
  switch (num) {
    case 1: //重新开票
      applyInvoiceHandle(row);
      break;
    case 2: //下载附件
      window.location.href = row.pdf;
      break;
    default:
      break;
  }
};

//重新开票
let applyInvoiceHandle = async (row) => {
  let resp = await proxy.$utils.confirmTips("是否确定重新发起开票?");
  if (!resp) return;
  await proxy.$apis.applyInvoice({
    type: "again",
    data: row,
  });
  proxy.$utils.showToast("已重新开票,请稍后再看");
  setTimeout(() => {
    getInfo();
  }, 1500);
};

async function exportExcel() {
  try {
    fileLoading.value = true;
    // let list = await proxy.$apis.invoicingRecord({
    //   type: "query",
    //   data: formInline.value,
    // });
    let list = proxy.$utils.deepcopy(selectedArr.value);
    let data = [];
    list.forEach((element) => {
      data.push({
        订单流水号: element.ddlsh,
        课程名称: curriculumFormat(element.curriculum_info.curriculum_id),
        购买方名称: element.gmfMc,
        购买方纳税人识别号: element.gmfNsrsbh,
        购买方手机号: element.gmfMobile || element.invoiceUser_info.mobile,
        购买方邮箱: element.gmfEmail,
        商品金额: element.detailParam[0].je,
        税率: element.detailParam[0].slv * 100 || 1,
        开票申请时间: proxy.$utils.dateTimeFormateFn(
          element.add_time || element._add_time,
          "all"
        ),
        开票状态: element._status,
        发票号码: element.qdfphm,
        开票异常原因: element.ycyy,
      });
    });
    let cols = []; //设置表头样式
    list.forEach((element) => {
      cols.push({ wch: 30 });
    });
    let query = {
      jsonData: data,
      cols,
    };
    await proxy.$utils.exportToExcel(query, "开票记录");
  } catch (error) {
    console.log("99999", error);
  } finally {
    fileLoading.value = false;
  }
}

watch(
  () => formInline.value.year,
  (newValue, oldValue) => {
    if (newValue) search();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.content {
  margin: 20px;
  .actionBtn {
    margin-bottom: 15px;
  }
}
</style>
